<?php
/**
 * Created by PhpStorm.
 * User: linhongzhao
 * Date: 18-5-11
 * Time: 上午8:13
 */

namespace EFrame;

class Config
{

    protected $configs = [];

    /**
     * Config constructor.
     * @param string $path 配置文件路径
     */
    public function __construct($path = __DIR__ . '/config.php')
    {
        $this->configs = require $path;
    }

    public function set($path, $value) {
        $keys = explode('.', $path);
        $tmp = &$this->configs;
        while ($key=array_shift($keys)) {
            if (!isset($tmp[$key])) {
                while ($key=array_shift($keys)) {
                    $tmp[$key] = [];
                }
            }
            $tmp = &$tmp[$key];
        }
        $tmp = $value;
        return true;
    }

    /**
     * 获取需要的配置, 参数$path为空时表示获取所有配置
     * @param null|string $path 配置路径 key1.key2表示寻找config[key1][key2]
     * @return array|mixed|null
     */
    public function get($path = null) {
        if ($path === null) {
            return $this->configs;
        }
        $keys = explode('.', $path);
        $tmp = &$this->configs;
        while ($key=array_shift($keys)) {
            if (!isset($tmp[$key])) {
                return null;
            }
            $tmp = &$tmp[$key];
        }
        return $tmp;
    }
}